import joplin from 'api';
import JoplinData from 'api/JoplinData';
import { ContentScriptType, Path, SettingItem, SettingItemType } from 'api/types';
import { setupDatabase,DB_getTagByTitle } from './database';

async function getAll(api: JoplinData, path: Path, query: any): Promise<any[]> {
	query.page = 1;
	let response = await api.get(path, query);
	let result = !!response.items ?  response.items : [];
	while (!!response.has_more) {
		query.page += 1;
		response = await api.get(path, query);
		result = result.concat(response.items);
	}
	return result;
}

joplin.plugins.register({
	onStart: async function() {
		await joplin.settings.registerSection('Inline Tags', {
			description: 'Inline Tags Plugin Settings',
			label: 'Inline Tags',
			iconName: 'fas fa-hashtag'
		});
		await joplin.settings.registerSettings({
			'keepText': {
				public: true,
				section: 'Inline Tags',
				type: SettingItemType.Bool,
				value: true,
				label: 'Keep #tag text in editor',
			}
		});

		await joplin.contentScripts.register(
			ContentScriptType.CodeMirrorPlugin,
			'inlineTags',
			'./InlineTagsPlugin.js'
		);

		await joplin.contentScripts.register(
			ContentScriptType.MarkdownItPlugin,
			'taglevellink',
			'./taglevellinkPlugin.js'
		);
		// onMessage 消息处理，不同插件，不同拦截
		// 类似一个后台一样，可以获取数据，可以执行交互命令。render只有样式处理。逻辑要messge和js 处理和发起
		await joplin.contentScripts.onMessage('taglevellink', async (message: any) => {
			const selectedNoteIds = await joplin.workspace.selectedNoteIds();
			const noteId = selectedNoteIds[0];
			let msg = {}
			// console.log(message)
			if(message.name === 'findTags'){
				let title = message.title.replace('\n','').replace('#','')
				//是否为多层级
				
				let titlearr = message.title.split("\\")
				let alltitle = []
				for(let title1 of titlearr){
					let title2 = title1.split("、")
					alltitle = alltitle.concat(title2)
				}
				console.log(alltitle)
				let findtags = await DB_getTagByTitle(alltitle[alltitle.length-1])
				if(findtags && findtags.length>0){
					let tag = findtags[0]
					console.log('indexts:tagClick:'+tag.id )
					joplin.commands.execute("openTag", tag.id)
					msg['code'] = 'succ';
				}else{
					msg['code'] = 'notag';
					msg['msg'] = '没有对应标签\''+title+'\'，请确认'
				}

			}
			return msg
		})

		await joplin.contentScripts.onMessage('inlineTags', async (message: any) => {
			const selectedNoteIds = await joplin.workspace.selectedNoteIds();
			const noteId = selectedNoteIds[0];

			if (message.command === 'getTags') {
				// let allTags = await getAll(joplin.data, ['tags'], { fields: ['id', 'title'], page: 1 });
				// 数据库获取，增加fulltitle显示，展示上下级
				let allTags = await setupDatabase()
				const noteTags: string[] =
					(await getAll(joplin.data, ['notes', noteId, 'tags'], { fields: ['id'], page: 1 })).map(t => t.id);
				//把当前已经打过了的标签去掉了，不能重复打
				allTags = allTags.filter(t => !noteTags.includes(t.id));
				
				const keepText: boolean = await joplin.settings.value('keepText');
				return {
					tags: allTags,
					keepText: keepText
				}
			} else if (message.command === 'setTag') {
				await joplin.data.post(['tags', message.tag.id, 'notes'], null, {
					id: noteId
				});
			} else if (message.command === 'newTag') {
				//是否为多层级
				let titlearr = message.name.split("\\")
				let alltitle = []
				for(let title1 of titlearr){
					let title2 = title1.split("、")
					alltitle = alltitle.concat(title2)
				}

				console.log(alltitle)
				let parentid = '';
				// 循环每个多层级
				for(let title of alltitle){
					let isnew = false
					let findtag = null
					// 如果含有“/”
					if(alltitle.length > 0){
						// 数据库查询，无判断是否为新增
						let findtags = await DB_getTagByTitle(title)
						if(findtags.length == 0){
							isnew = true
						}else{
							findtag = findtags[0]
						}
					}
					if(isnew){
						if(title){
							// console.log('new tag:'+title)
							const newTag = await joplin.data.post(['tags'], null, {
								title: title,parent_id:parentid
							});
							await joplin.data.post(['tags', newTag.id, 'notes'], null, {
								id: noteId
							});
							// 为下一个tag做准备，设置下一个的上级id
							parentid = newTag.id
						}
					}else{
						// 如果以后tag，上级不是现在的上级，则更新
						if(parentid != findtag.parent_id){
							joplin.data.put(['tags',findtag.id], null, {
								parent_id:parentid
							});
						}
						// 如果查询的tag不为空，中间过程的，也同步 关联到文章上
						if(findtag.title){
							await joplin.data.post(['tags', findtag.id, 'notes'], null, {
								id: noteId
							});
						}
						// 为下一个tag做准备，设置下一个的上级id
						parentid = findtag.id
					}
					

				}
			}
		});
	},
});
